package com.ys.erp.stage_user_service.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ys.erp.common.enums.EnableEnum;
import com.ys.erp.common.util.MoneyUtil;
import com.ys.erp.common.util.YsThread;
import com.ys.erp.entity.data.bean.CatMoneyOrder;
import com.ys.erp.entity.data.bean.CatMoneyPupGear;
import com.ys.erp.entity.data.bean.UserCat;
import com.ys.erp.entity.data.bean.UserCatExt;
import com.ys.erp.entity.service.ICatMoneyOrderService;
import com.ys.erp.entity.service.ICatMoneyPupGearService;
import com.ys.erp.entity.service.IUserCatExtService;
import com.ys.erp.entity.service.IUserCatService;
import com.ys.erp.framework.bean.dto.StageEmpDTO;
import com.ys.erp.framework.exception.YsException;
import com.ys.erp.framework.response.PageDTO;
import com.ys.erp.framework.response.ResponseDTO;
import com.ys.erp.stage_user_service.bean.condition.UserMoneyCondition;
import com.ys.erp.stage_user_service.bean.vo.CatMoneyOrderTotalVO;
import com.ys.erp.stage_user_service.bean.vo.InMoneySettingVO;
import com.ys.erp.stage_user_service.bean.vo.PageInCatMoneyRecordVO;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * @author lwj
 * @date 2025/5/16
 */
@RequiredArgsConstructor
@Service
@RefreshScope
@Log4j
public class UserMoneyService {

    private final ICatMoneyOrderService iCatMoneyOrderService;

    private final IUserCatExtService iUserCatExtService;

    private final IUserCatService iUserCatService;

    private final ICatMoneyPupGearService iCatMoneyPupGearService;

    /**
     * 分页充值幺币记录
     *
     * @param empDto                登录员工
     * @param con                   请求体
     * @return                      幺币充值记录
     */
    public PageDTO<PageInCatMoneyRecordVO> pageInRecord(StageEmpDTO empDto, UserMoneyCondition.PageInCatMoneyRecordCon con) {
        List<Long> filterUserCatIdList = new ArrayList<>();
        CompletableFuture<Boolean> extFilterFuture = YsThread.execute(() -> {
            QueryWrapper<UserCatExt> extQw = new QueryWrapper<>();
            extQw.lambda().select(UserCatExt::getId);
            if (ObjectUtils.isEmpty(con.getPeriodMoney()) && ObjectUtils.isEmpty(con.getShopCode())) {
                return true;
            }
            if (ObjectUtils.isNotEmpty(con.getPeriodMoney())) {
                extQw.lambda().eq(UserCatExt::getPeriodMoney, con.getPeriodMoney());
            }
            if (ObjectUtils.isNotEmpty(con.getShopCode())) {
                extQw.lambda().eq(UserCatExt::getShopCode, con.getShopCode());
            }
            List<Long> longs = iUserCatExtService.listObjs(extQw, it -> Long.valueOf(it.toString()));
            if (longs.isEmpty()) {
                filterUserCatIdList.add(-1L);
            }
            filterUserCatIdList.addAll(longs);
            return true;
        });
        Page<CatMoneyOrder> orderPage = new Page<>(con.getCurrent(), con.getSize());
        //构造参数
        QueryWrapper<CatMoneyOrder> orderQw = new QueryWrapper<>();
        orderQw.lambda().eq(CatMoneyOrder::getPayStatus, CatMoneyOrder.Enums.PAY_SUCCESS.name());
        if (ObjectUtils.isNotEmpty(con.getStartPayDate())) {
            orderQw.lambda().ge(CatMoneyOrder::getPayTime, con.getStartPayDate() + " 00:00:00");
        }
        if (ObjectUtils.isNotEmpty(con.getEndPayDate())) {
            orderQw.lambda().le(CatMoneyOrder::getPayTime, con.getEndPayDate() + " 23:59:59");
        }
        if  (ObjectUtils.isNotEmpty(con.getGiftType())) {
            if ("-1".equals(con.getGiftType())){
                orderQw.lambda().isNull(CatMoneyOrder::getGiftType);
            }else {
                orderQw.lambda().eq(CatMoneyOrder::getGiftType, con.getGiftType());
            }
        }
        if (ObjectUtils.isNotEmpty(con.getUserId())) {
            orderQw.lambda().eq(CatMoneyOrder::getUserId, con.getUserId());
        }
        extFilterFuture.join();
        if (!filterUserCatIdList.isEmpty() && filterUserCatIdList.getFirst() == -1L) {
            return new PageDTO<>(1L, 0L, new ArrayList<>());
        }
        if (!filterUserCatIdList.isEmpty()) {
            orderQw.lambda().in(CatMoneyOrder::getUserCatId, filterUserCatIdList);
        }
        orderQw.lambda().orderByDesc(CatMoneyOrder::getId);
        //查询
        Page<CatMoneyOrder> page = iCatMoneyOrderService.page(orderPage, orderQw);
        if (page.getRecords().isEmpty()) {
            return new PageDTO<>(1L, 0L, new ArrayList<>());
        }
        List<Long> userCatIdList = page.getRecords().stream().map(CatMoneyOrder::getUserCatId).collect(Collectors.toList());
        Map<Long, UserCat> userCatMap = iUserCatService.listByIds(userCatIdList).stream()
                .collect(Collectors.toMap(UserCat::getId, userCat -> userCat));

        //整理数据
        List<PageInCatMoneyRecordVO> collect = page.getRecords().stream()
                .map(order -> {
                    PageInCatMoneyRecordVO vo = new PageInCatMoneyRecordVO();
                    UserCat userCat = userCatMap.get(order.getUserCatId());
                    if (Objects.isNull(userCat)) {
                        return vo;
                    }
                    vo.setPayTime(order.getPayTime());
                    vo.setMoney(MoneyUtil.long2Str(order.getActualAmount()));
                    vo.setUserId(order.getUserId());
                    vo.setCatCode(userCat.getCatCode());
                    vo.setPeriodMoney(userCat.getUserFeeRemark());
                    vo.setShopName(userCat.getShopName());
                    vo.setGiftAmount(MoneyUtil.long2Str(order.getGiftAmount()));
                    vo.setGiftType(order.getGiftType());
                    return vo;
                }).collect(Collectors.toList());
        return new PageDTO<>(page.getCurrent(), page.getTotal(), collect);
    }

    /**
     * 幺币充值次数及总金额
     *
     * @param empDto                登录员工
     * @param con                   筛选条件
     * @return                      统计
     */
    public CatMoneyOrderTotalVO catMoneyOrderTotal(StageEmpDTO empDto, UserMoneyCondition.PageInCatMoneyRecordCon con) {
        con.setSize(100000);
        con.setCurrent(1);
        PageDTO<PageInCatMoneyRecordVO> pageCatMoneyRechargeRecordVOPageDTO = pageInRecord(empDto, con);
        //整理数据
        CatMoneyOrderTotalVO vo = new CatMoneyOrderTotalVO();
        vo.setCount(pageCatMoneyRechargeRecordVOPageDTO.getTotal());
        long sum = pageCatMoneyRechargeRecordVOPageDTO.getRecords().stream()
                .mapToLong(it -> MoneyUtil.str2Long(it.getMoney()))
                .sum();
        vo.setTotalMoney(MoneyUtil.long2Str(sum));
        return vo;
    }

    /**
     * 充值幺币配置集
     *
     * @param empDto                登录员工
     * @return                      配置集
     */
    public List<InMoneySettingVO> inMoneySettingList(StageEmpDTO empDto) {
        QueryWrapper<CatMoneyPupGear> catMoneyPupGearQw = new QueryWrapper<>();
        catMoneyPupGearQw.lambda().eq(CatMoneyPupGear::getDelFlag, EnableEnum.NO.getEnable());
        catMoneyPupGearQw.lambda().orderByDesc(CatMoneyPupGear::getId);
        List<CatMoneyPupGear> list = iCatMoneyPupGearService.list(catMoneyPupGearQw);
        ArrayList<InMoneySettingVO> results = new ArrayList<>();
        for (CatMoneyPupGear catMoneyPupGear : list) {
            InMoneySettingVO catMoneyGearVO = new InMoneySettingVO();
            catMoneyGearVO.setId(catMoneyPupGear.getId());
            catMoneyGearVO.setPupAmount(MoneyUtil.long2Str(catMoneyPupGear.getPupAmount()));
            catMoneyGearVO.setGiftAmount(MoneyUtil.long2Str(catMoneyPupGear.getGiftAmount()));
            catMoneyGearVO.setGiftType(catMoneyPupGear.getGiftType());
            catMoneyGearVO.setText(catMoneyPupGear.getText());
            catMoneyGearVO.setCreateTime(catMoneyPupGear.getCreateTime());
            catMoneyGearVO.setIsDisabled(catMoneyPupGear.getIsDisabled());
            results.add(catMoneyGearVO);
        }
        return results;
    }

    /**
     * 新增或更新幺币配置
     *
     * @param empDto                登录员工
     * @param con                   请求体
     */
    public void addOrUpdateInMoneySetting(StageEmpDTO empDto, UserMoneyCondition.AddOrUpDateInMoneySettingCon con) {
        if (ObjectUtils.isEmpty(con.getId())) {
            CatMoneyPupGear catMoneyPupGear = new CatMoneyPupGear();
            catMoneyPupGear.setPupAmount(MoneyUtil.str2Long(con.getPayMoney()));
            catMoneyPupGear.setText(con.getText());
            catMoneyPupGear.setGiftAmount(MoneyUtil.str2Long(con.getGiftMoney()));
            catMoneyPupGear.setIsDisabled(con.getIsDisable());
            catMoneyPupGear.setGiftType(con.getGiftType());
            catMoneyPupGear.setEmpId(empDto.getId());
            iCatMoneyPupGearService.save(catMoneyPupGear);
            return;
        }

        CatMoneyPupGear gear = iCatMoneyPupGearService.getById(con.getId());
        if (Objects.isNull(gear)) {
            throw new YsException(new ResponseDTO<>(-1, "数据不存在", null));
        }

        gear.setIsDisabled(con.getIsDisable());
        gear.setGiftType(con.getGiftType());
        gear.setPupAmount(MoneyUtil.str2Long(con.getPayMoney()));
        gear.setGiftAmount(MoneyUtil.str2Long(con.getGiftMoney()));
        gear.setEmpId(empDto.getId());
        gear.setText(con.getText());
        iCatMoneyPupGearService.updateById(gear);
    }


}
